//
//  UIImage+AsyncDraw.swift
//  sinaweibo
//
//  Created by WGP on 16/4/18.
//  Copyright © 2016年 WGP. All rights reserved.
//

import UIKit

extension UIImage
{
//    异步绘制图片
    func GP_AsynDrawImage(var size: CGSize?, bgColor: UIColor? = UIColor.whiteColor(), isCorner: Bool = true, drawFinished:(image: UIImage) -> ())
    {
        dispatch_async(dispatch_get_global_queue(0, 0)) { () -> Void in
            
           if size == nil
           {
                size = self.size
            }
            
            let rect = CGRect(origin: CGPointZero, size: size!)
            
//            opaque:不透明度,ture 表示不透明,false表示透明
            UIGraphicsBeginImageContextWithOptions(size!, bgColor != nil, UIScreen.mainScreen().scale)
            
            bgColor?.setFill()
            UIRectFill(rect)
            
            if isCorner
            {
                let path = UIBezierPath(ovalInRect: rect)
                
//                让后面绘制的元素在路径里面
                path.addClip()
            }
            
            self.drawInRect(rect)
            
            let newImage = UIGraphicsGetImageFromCurrentImageContext()
            
            UIGraphicsEndImageContext()
            
            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                
                drawFinished(image: newImage)
                
            })
        }
    }
}

